<template>
  <div class="user_wrapper">
    <el-space fill style="width: 100%">
      <el-card>
        <el-row>
          <el-col :span="6">
            <el-form :inline="true">
              <el-form-item label="用户名">
                <el-input v-model="keyword" placeholder="请输入用户名" />
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="18" style="text-align: right">
            <el-space style="margin-bottom: 20px">
              <el-button type="primary" @click="searchUser">搜索</el-button>
              <el-button type="default" @click="resetSearch">重置</el-button>
            </el-space>
          </el-col>
        </el-row>
      </el-card>
      <el-card class="spu_card_table common_card_wrapper">
        <el-space style="margin-bottom: 20px">
          <el-button type="primary" icon="plus" @click="addUser">
            添加
          </el-button>
          <el-button
            type="danger"
            :disabled="!multipleSelection.length"
            @click="batchDelUsers"
          >
            批量删除
          </el-button>
        </el-space>

        <el-table
          :data="tableData"
          :border="true"
          v-loading="loading"
          element-loading-text="加载中..."
          height="650px"
          row-key="id"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column type="index" label="#" width="100" align="center" />
          <el-table-column prop="username" label="用户名" width="300" />
          <el-table-column prop="name" label="用户名称" width="300" />
          <el-table-column
            prop="roleName"
            :show-overflow-tooltip="true"
            label="用户角色"
            width="300"
          />
          <el-table-column prop="createTime" label="创建时间" width="300" />
          <el-table-column prop="updateTime" label="更新时间" width="300" />
          <el-table-column prop="action" label="操作" width="350" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" icon="user" @click="setRole(row)">
                分配角色
              </el-button>
              <el-button type="primary" icon="edit" @click="editUser(row)">
                编辑
              </el-button>
              <el-button type="primary" icon="delete" @click="delUser(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="common_pagination"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[30, 50, 100]"
          :small="small"
          :disabled="disabled"
          :background="background"
          layout="prev, pager, next, jumper,->,total, sizes"
          :total="total"
          @size-change="sizeChange"
          @current-change="getUserList"
        />
      </el-card>
    </el-space>
    <!-- 添加用户 -->
    <Drawer
      :visible="drawerUserVisible"
      :title="drawerUserTitle"
      :width="drawerUserWidth"
      :modal="drawerUserModal"
      @close="closeDrawer"
    >
      <template #drawer-content>
        <el-form
          :model="userForm"
          :rules="rules"
          label-width="auto"
          ref="user"
          style="max-width: 600px; margin: auto"
        >
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="userForm.username"
              placeholder="请输入用户名字"
              :disabled="!isAdd"
            />
          </el-form-item>
          <el-form-item label="用户名称" prop="name">
            <el-input v-model="userForm.name" placeholder="请输入用户名称" />
          </el-form-item>
          <el-form-item label="用户密码" prop="password" v-if="isAdd">
            <el-input
              v-model="userForm.password"
              placeholder="请输入用户密码"
            />
          </el-form-item>
        </el-form>
      </template>
      <template #drawer-footer>
        <el-space wrap>
          <el-button type="primary" @click="save" :loading="saveloading">
            保存
          </el-button>
          <el-button @click="closeDrawer(false)">取消</el-button>
        </el-space>
      </template>
    </Drawer>
    <!-- 分配角色 -->
    <Drawer
      :visible="drawerRoleVisible"
      :title="drawerRoleTitle"
      :width="drawerRoleWidth"
      :modal="drawerRoleModal"
      @close="closeRoleDrawer"
    >
      <template #drawer-content>
        <el-form
          :model="roleForm"
          label-width="auto"
          ref="user"
          style="max-width: 600px; margin: auto"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="roleForm.username" :disabled="true" />
          </el-form-item>
          <el-form-item label="角色列表" class="form-item">
            <el-checkbox
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
            >
              全选
            </el-checkbox>
            <el-checkbox-group
              v-model="roleForm.roleIdList"
              @change="handleCheckedCitiesChange"
            >
              <el-checkbox
                v-for="item in roleArr"
                :label="item.roleName"
                :value="item.id"
                :key="item.id"
              />
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </template>
      <template #drawer-footer>
        <el-space wrap>
          <el-button type="primary" @click="saveRole" :loading="saveloading">
            保存
          </el-button>
          <el-button @click="closeRoleDrawer(false)">取消</el-button>
        </el-space>
      </template>
    </Drawer>
  </div>
</template>

<script setup lang="ts" name="User">
import { ref, onMounted, nextTick } from 'vue'
import {
  reqUserList,
  addOrUpdateUserReq,
  delUserReq,
  batchDelSpuReq,
  reqUserRole,
  reqDoAssignRole
} from '@/api/acl/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useLayoutStore } from '@/stores/modules/setting'
import '@/styles/common/index.less'

// 校验用户名回调函数
const validatorUserName = (rule: any, value: any, callback: any) => {
  // 用户名|名称长度至少五位
  if (value.trim().length >= 5) {
    callback()
  } else {
    callback('用户名至少五位')
  }
}

// 校验用户名称回调函数
const validatorName = (rule: any, value: any, callback: any) => {
  // 用户名|名称长度至少五位
  if (value.trim().length >= 5) {
    callback()
  } else {
    callback('用户名称至少五位')
  }
}

// 校验用密码回调函数
const validatorPassword = (rule: any, value: any, callback: any) => {
  // 用户名|名称长度至少五位
  if (value.trim().length >= 6) {
    callback()
  } else {
    callback('密码至少六位')
  }
}

onMounted(() => {
  getUserList()
})

let layoutStore = useLayoutStore()
let tableData = ref<any>([])
const currentPage = ref(1)
const pageSize = ref(30)
const small = ref(false)
const background = ref(true)
const disabled = ref(false)
let total = ref(0)
let loading = ref(false)
const multipleSelection = ref<any[]>([])
let keyword = ref('')
let drawerUserVisible = ref(false)
let drawerUserTitle = ref('添加用户')
let drawerUserWidth = ref(800)
let drawerUserModal = ref(true)
let drawerRoleVisible = ref(false)
let drawerRoleTitle = ref('分配角色')
let drawerRoleWidth = ref(800)
let drawerRoleModal = ref(true)
const userForm = ref<any>({
  username: '',
  name: '',
  password: ''
})
const rules = {
  username: [
    {
      required: true,
      message: '用户名不能为空',
      trigger: 'blur'
    },
    {
      trigger: 'blur',
      validator: validatorUserName
    }
  ],
  name: [
    {
      required: true,
      message: '用户名称不能为空',
      trigger: 'blur'
    },
    {
      validator: validatorName,
      trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      message: '密码不能为空',
      trigger: 'blur'
    },
    {
      validator: validatorPassword,
      trigger: 'blur'
    }
  ]
}
const roleForm = ref<any>({
  username: '',
  id: '',
  roleIdList: []
})
let isAdd = ref(true)
const user = ref()
let saveloading = ref(false)
let roleArr = ref<any>([])
const checkAll = ref(false)
const isIndeterminate = ref(false)

// 获取列表数据
const getUserList = async (pager = 1) => {
  currentPage.value = pager
  loading.value = true
  let res: any = await reqUserList(
    currentPage.value,
    pageSize.value,
    keyword.value
  )
  if (res.code === 200) {
    tableData.value = res.data.records
    total.value = res.data.total
    loading.value = false
  } else {
    ElMessage.error(res.message)
    loading.value = false
  }
}

const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}

// 分页器 自定义条数方法
const sizeChange = () => {
  getUserList()
}

// 搜索
const searchUser = () => {
  getUserList()
}

// 重置
const resetSearch = () => {
  layoutStore.refresh = !layoutStore.refresh
}

// 添加
const addUser = () => {
  drawerUserVisible.value = true
  isAdd.value = true
  userForm.value = {
    username: '',
    name: '',
    password: ''
  }
}

// 编辑
const editUser = (data: any) => {
  Object.assign(userForm.value, data)
  drawerUserVisible.value = true
  drawerUserTitle.value = '编辑用户'
  isAdd.value = false
}

// 分配角色
const setRole = (data: any) => {
  drawerRoleVisible.value = true
  getUserRole(data.id)
  Object.assign(roleForm.value, data)
}

// 获取用户角色
const getUserRole = async (id: any) => {
  let res: any = await reqUserRole(id)
  if (res.code === 200) {
    roleArr.value = res.data.allRolesList
    roleForm.value.roleIdList = res.data.assignRoles.map((o: any) => o.id)
    const checkedCount = roleForm.value.roleIdList.length
    checkAll.value = checkedCount === roleArr.value.length
    isIndeterminate.value =
      checkedCount > 0 && checkedCount < roleArr.value.length
  } else {
    ElMessage.error(res.data ? res.data : res.message)
  }
}

// 全选
const handleCheckAllChange = (val: boolean) => {
  roleForm.value.roleIdList = val ? roleArr.value.map((o: any) => o.id) : []
  isIndeterminate.value = false
}

// 单选
const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === roleArr.value.length
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < roleArr.value.length
}

// 单个删除方法
const delUserMethod = async (id: any) => {
  let res: any = await delUserReq(id)
  if (res.code === 200) {
    ElMessage.success(res.message)
    getUserList(
      tableData.value.length > 1 ? currentPage.value : currentPage.value - 1
    )
  } else {
    ElMessage.error(res.data ? res.data : res.message)
  }
}

// 单个删除
const delUser = (data: any) => {
  ElMessageBox.confirm(`确定删除${data.username}吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    delUserMethod(data.id)
  })
}

// 批量删除方法
const batchDelUserMethod = async (ids: any) => {
  let res: any = await batchDelSpuReq(ids)
  if (res.code === 200) {
    ElMessage.success(res.message)
    getUserList(
      tableData.value.length > 1 ? currentPage.value : currentPage.value - 1
    )
  } else {
    ElMessage.error(res.data ? res.data : res.message)
  }
}

// 批量删除
const batchDelUsers = () => {
  const ids = multipleSelection.value.map((item: any) => item.id)
  ElMessageBox.confirm(`确定删除已选的${ids.length}条数据吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    batchDelUserMethod(ids)
  })
}

// 新增/编辑方法
const addOrUpdateUserMethod = async (data: any) => {
  let res: any = await addOrUpdateUserReq(data)
  if (res.code === 200) {
    ElMessage.success(res.message)
    getUserList(data.id ? currentPage.value : 1)
    closeDrawer(false)
  } else {
    ElMessage.error(res.data ? res.data : res.message)
  }
  saveloading.value = false
}

// 保存
const save = async () => {
  await user.value.validate(async (valid: any) => {
    if (valid) {
      saveloading.value = true
      addOrUpdateUserMethod(userForm.value)
    }
  })
}

// 保存角色分配
const saveRole = async () => {
  saveloading.value = true
  const { id, roleIdList } = roleForm.value
  const form = {
    userId: id,
    roleIdList
  }
  let res: any = await reqDoAssignRole(form)
  if (res.code === 200) {
    ElMessage.success(res.message)
    getUserList(currentPage.value)
    closeRoleDrawer(false)
  } else {
    ElMessage.error(res.data ? res.data : res.message)
  }
  saveloading.value = false
}

// drawer user 回调
const closeDrawer = (value: boolean) => {
  drawerUserVisible.value = value
  nextTick(() => {
    user.value.resetFields()
  })
}

// drawer role 回调
const closeRoleDrawer = (value: boolean) => {
  drawerRoleVisible.value = value
}
</script>

<style lang="less">
.form-item {
  .el-form-item__content {
    display: block !important;
  }
}
</style>
